<template>
	<view class="wanl-order-list">
		<goods-tabs :list="navList1" :is-scroll="false" v-model="tabCurrentIndex" name="text_show"
			@change="tabClick"></goods-tabs>
		<swiper :current="tabCurrentIndex" style="height: calc(100% - 80rpx)" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tag, key) in navList" :key="tag.state">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<wanl-empty text="没有找到任何订单" v-if="tag.loaded === true && tag.list.length === 0" />
					<!-- 订单列表 -->
					<view v-for="(order, okey) in tag.list" :key="order.id" class="order-item radius-bock">

						<view v-if="order.is_take">
							<view v-for="(order1,okey1) in order.orders" :key="okey1">
								<view class="head">
									<view class="shop wanl-gray" @tap="onShop(order1.shop_id)">
										<text class="wlIcon-dianpu1 wanl-black"></text>
										<text class="wanl-black margin-lr-xs text-30">{{ order1.shop.shopname }}</text>
										<text class="wlIcon-fanhuigengduo text-sm"></text>
									</view>
									<view class="margin-right-bj text-sm">
										<text class="state"
											:style="{ color: order1.stateTipColor }">{{ order1.stateTip }}</text>
										<text v-if="order1.state === 7" class="margin-left-sm wlIcon-lajitong"
											@tap="deleteOrder(order1.id,okey)"></text>
									</view>
								</view>
								<!-- 商品 -->
								<view class="goods-box" v-for="(goods, gkey) in order1.goods" :key="goods.id"
									@tap="order1Details(order1.id)">
									<view class="cu-avatar xl margin-right-bj radius"
										:style="{backgroundImage: 'url('+$wanlshop.oss(goods.image, 70, 70)+')'}">
									</view>
									<view class="content margin-right-bj">
										<view class="describe">

											<view class="text-cut-2">
												{{goods.title}}
											</view>
											<view class="wanl_sku text-min">
												<text class="wanl-gray-dark">{{goods.difference}}</text>
											</view>
										</view>
										<view class="parameter">
											<view class="text-price text-sm text-black">
												{{ goods.price }}
											</view>
											<view class="text-min wanl-gray">
												x {{ goods.number }}
											</view>
											<!-- 退款状态:0=未退款,1=退款中,2=待退货,3=退款完成 -->
											<view class="text-min text-yellow" v-if="goods.refund_status != 0">
												{{getRefund(goods.refund_status)}}
											</view>
										</view>
									</view>
								</view>
								<!-- 底部 -->
							</view>
							<view class="price-box text-sm flex">
								<view v-if="order.discount_price > 0" class="margin-right-sm wanl-gray">
									优惠：<text class="text-price">{{ order.discount_price }}</text></view>
								<view v-if="order.freight_price > 0" class="margin-right-sm wanl-gray">总运费：<text
										class="text-price">{{ order.freight_price }}</text></view>
								<view v-if="order.send_price > 0" class="margin-right-sm wanl-gray">秒送费：<text
										class="text-price">{{ order.send_price }}</text></view>
								<view>实付款：<text class="text-price">{{ order.price }}</text></view>
							</view>
							<view class="action-box padding-bottom-bj">
								<button class="cu-btn round line-black wanl-bg-orange" open-type="share"
									@click="() => df(order)">代付</button>
								<button class="cu-btn round margin-lr-bj-xx wanl-bg-orange"
									@click="() => paymentOrder(order)">立即支付</button>
							</view>

						</view>
						<block v-else>
							<view class="head">
								<view class="shop wanl-gray" @tap="onShop(order.shop_id)">
									<text class="wlIcon-dianpu1 wanl-black"></text>
									<text class="wanl-black margin-lr-xs text-30">{{ order.shop.shopname }}</text>
									<text class="wlIcon-fanhuigengduo text-sm"></text>
								</view>
								<view class="margin-right-bj text-sm">
									<text class="state"
										:style="{ color: order.stateTipColor }">{{ order.stateTip }}</text>
									<text v-if="order.state === 7" class="margin-left-sm wlIcon-lajitong"
										@tap="deleteOrder(order.id,okey)"></text>
								</view>
							</view>
							<!-- 商品 -->
							<view class="goods-box" v-for="(goods, gkey) in order.goods" :key="goods.id"
								@tap="orderDetails(order.id)">
								<view class="cu-avatar xl margin-right-bj radius"
									:style="{backgroundImage: 'url('+$wanlshop.oss(goods.image, 70, 70)+')'}"> </view>
								<view class="content margin-right-bj">
									<view class="describe">

										<view class="text-cut-2">
											{{goods.title}}
										</view>
										<view class="wanl_sku text-min">
											<text class="wanl-gray-dark">{{goods.difference}}</text>
										</view>
									</view>
									<view class="parameter">
										<view class="text-price text-sm text-black">
											{{ goods.price }}
										</view>
										<view class="text-min wanl-gray">
											x {{ goods.number }}
										</view>
										<!-- 退款状态:0=未退款,1=退款中,2=待退货,3=退款完成 -->
										<view class="text-min text-yellow" v-if="goods.refund_status != 0">
											{{getRefund(goods.refund_status)}}
										</view>
									</view>
								</view>
							</view>
							<!-- 底部 -->
							<view class="price-box text-sm flex">
								<view v-if="order.pay.discount_price > 0" class="margin-right-sm wanl-gray">优惠：<text
										class="text-price">{{ order.pay.discount_price }}</text></view>
								<view v-if="order.pay.freight_price > 0" class="margin-right-sm wanl-gray">总运费：<text
										class="text-price">{{ order.pay.freight_price }}</text></view>
								<view v-if="order.pay.send_price > 0" class="margin-right-sm wanl-gray">秒送费：<text
										class="text-price">{{ order.pay.send_price }}</text></view>
								<view>实付款：<text class="text-price">{{ order.pay.price }}</text></view>
							</view>

							<view class="action-box padding-bottom-bj" v-if="order.state == 1">
								<button class="cu-btn round line-black margin-lr-bj-xx"
									@tap="editAddress(order.id)">修改地址</button>
								<!-- merge_take 0 未合并订单 1 已合并（已代付） -->
								<button class="cu-btn round line-black" @tap="cancelOrder(order)"
									v-if="order.merge_take == 0">取消订单</button>
								<button class="cu-btn round margin-lr-bj-xx wanl-bg-orange" @tap="goAssist(order)"
									v-if="order.help">助力</button>
								<button v-if="order.merge_take == 0" class="cu-btn round margin-lr-bj-xx wanl-bg-orange"
									@tap="paymentOrder(order)">立即支付</button>
							</view>
							<view class="action-box padding-bottom-bj" v-if="order.state == 2">
								<button class="cu-btn round line-black"
									@tap="toChat(order.shop_id,'',order.shop.user_id)">联系商家</button>
								<button class="cu-btn round margin-lr-bj wanl-bg-orange"
									@tap="editAddress(order.id)">修改地址</button>
							</view>

							<view class="action-box padding-bottom-bj" v-if=" order.state == 3 || order.state == 9">
								<view class="error f32 fb mr12" v-if="order.send_type == 5">
									取货码：{{order.pickup_code}}
								</view>
								<button class="cu-btn round line-black" @tap="onLogistics(order.id)">查看物流</button>
								<button v-if="order.send_type == 2" class="cu-btn round margin-lr-bj wanl-bg-orange"
									@tap="confirmOrder(order)">确认收货</button>
							</view>
							<view class="action-box padding-bottom-bj" v-if="order.state == 4 ">
								<button class="cu-btn round line-black" @tap="onLogistics(order.id)">查看物流</button>
								<button class="cu-btn round margin-lr-bj line-black"
									@tap="commentOrder(order.id)">评论订单</button>
							</view>
						</block>
					</view>
					<uni-load-more :status="tag.loadingType" :content-text="contentText" />
					<view class="edgeInsetBottom"></view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				order_ids: [],
				tabCurrentIndex: 0,
				navList1: [{
						state: 0,
						count: 0,
						text: '全部',
						text_show: '全部',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 1,
						count: 0,
						text: '待支付',
						text_show: '待支付',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 2,
						count: 0,
						text: '待发货',
						text_show: '待发货',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 3,
						count: 0,
						text: '待收货',
						text_show: '待收货',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 4,
						count: 0,
						text: '待评论',
						text_show: '待评论',
						loadingType: 'more',
						current_page: 1,
						list: []
					}

				],

				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 1,
						text: '待支付',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 2,
						text: '待发货',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 3,
						text: '待收货',
						loadingType: 'more',
						current_page: 1,
						list: []
					},
					{
						state: 4,
						text: '待评论',
						loadingType: 'more',
						current_page: 1,
						list: []
					}
					// ,{
					// 	state: 7,
					// 	text: '已关闭',
					// 	loadingType: 'more',
					// 	current_page: 1,
					// 	list: []
					// }
				],
				contentText: {
					contentdown: ' ',
					contentrefresh: '正在加载...',
					contentnomore: ''
				},
				triggered1: false,
			};
		},
		onShow() {
			this.getloadData()
		},
		onLoad(options) {
			this.getrefresh()
			if (!options.state) {
				options.state = 0;
			}
			this.tabCurrentIndex = +options.state;

		},
		methods: {
			df(data) {
				this.order_ids = data.orders.map(a => a.id)
			},
			getrefresh() {
				this.$api.post({
					url: '/wanlshop/user/refresh',
					success: res => {
						this.navList1[1].count = res.statistics.order.pay
						this.navList1[2].count = res.statistics.order.delive
						this.navList1[3].count = res.statistics.order.receiving
						this.navList1[4].count = res.statistics.order.evaluate
					}

				})

			},
			getloadData() {
				if (this.triggered1 === false) {
					this.triggered1 = true
					let navItem = this.navList[this.tabCurrentIndex];
					navItem.current_page = 1
					navItem.loadingType = 'more'
					navItem.list = []
					setTimeout(() => {
						this.getrefresh()
						this.loadData()
						this.triggered1 = false
					}, 100)
				}
			},
			//获取订单列表
			loadData(source) {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;
				//判断是否最后一页
				if (navItem.loadingType == 'noMore') {
					return;
				}
				//tab切换只有第一次需要加载数据
				if (source === 'tabChange' && navItem.loaded === true) {
					return;
				}
				//防止重复加载
				if (navItem.loadingType === 'loading') {
					return;
				}
				navItem.loadingType = 'loading';
				// 获取列表
				this.$api.get({
					url: '/wanlshop/order/getOrderList',
					data: {
						state: state,
						page: navItem.current_page
					},
					success: res => {
						navItem.current_page = res.current_page; //当前页码
						if (res.last_page === res.current_page) {
							navItem.loadingType = 'noMore';
						} else {
							navItem.loadingType = 'more';
							navItem.current_page++;
						}
						let list = res.data.filter(item => {
							if (item.is_take) {
								let price = 0,
									freight_price = 0,
									discount_price = 0,
									send_price = 0

								item.orders.forEach(orders => {
									orders = Object.assign(orders, this.orderStateExp(orders
										.state));
									price = this.$wanlshop.bcadd(price, orders.pay.price)
									freight_price = this.$wanlshop.bcadd(freight_price, orders
										.pay.freight_price)
									discount_price = this.$wanlshop.bcadd(discount_price,
										orders.pay.discount_price)
									send_price = this.$wanlshop.bcadd(send_price,
										orders.pay.send_price)
									if (state === 0) {
										//0为全部订单
										return item;
									}
									return item;
									return item.state === state;
								})
								item.price = price
								item.freight_price = freight_price
								item.send_price = send_price
								item.discount_price = discount_price
								return item;
							} else {
								//添加不同状态下订单的表现形式
								item = Object.assign(item, this.orderStateExp(item.state));
								//演示数据所以自己进行状态筛选
								if (state === 0) {
									//0为全部订单
									return item;
								}
								return item;
								return item.state === state;
							}

						});
						list.forEach(item => {
							navItem.list.push(item);
						});
						//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
						this.$set(navItem, 'loaded', true);
					}
				});
			},
			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.getloadData()
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
				this.getloadData()
			},
			//删除订单
			deleteOrder(order_id, key) {
				uni.showLoading({
					title: '请稍后'
				});
				this.$api.post({
					url: '/wanlshop/order/delOrder',
					data: {
						id: order_id
					},
					success: res => {
						this.getloadData()
						uni.hideLoading();
					}
				});
			},
			//取消订单- 设置为7 -全局
			cancelOrder(item) {
				uni.showLoading({
					title: '请稍后'
				});
				// 获取列表
				this.$api.post({
					url: '/wanlshop/order/cancelOrder',
					data: {
						id: item.id
					},
					success: res => {
						let {
							stateTip,
							stateTipColor
						} = this.orderStateExp(7);
						item = Object.assign(item, {
							state: 7,
							stateTip,
							stateTipColor
						});
						this.$store.commit('statistics/order', {
							pay: this.$store.state.statistics.order.pay - 1,
							whole: this.$store.state.statistics.order.whole - 1
						});
						// 取消订单后删除待付款中该项，并修改全部中的状态 1.0.2升级
						let list = this.navList[1].list;
						let index = list.findIndex(val => val.id === item.id);
						index !== -1 && list.splice(index, 1);
						// 删除后修改全部中的为7
						if (this.tabCurrentIndex == 1) {
							let list = this.navList[0].list;
							let index = list.findIndex(val => val.id === item.id);
							if (index !== -1) {
								list[index].state = 7;
							}
						}
						uni.hideLoading();
						this.getloadData()
					}
				});
			},
			commentOrder(id) {
				this.$wanlshop.to('/pages/user/order/comment?order_id=' + id);
			},
			goAssist(order) { //助力
				this.$wanlshop.to(`/pages/user/assist/assist?order_id=${order.id}`);
			},
			//支付订单
			paymentOrder(order) {
				if (order.is_take) {
					let ids = order.orders.map(a => a.id)
					this.$wanlshop.to(
						`/pages/user/money/pay?ids=${ids}&dffk=dffk`);

				} else {
					let help = order.is_help == 1 ? true : false //1是 0否
					this.$wanlshop.to(`/pages/user/money/pay?order_id=${order.id}&order_type=goods&help=${help}`);
				}
			},
			//确认收货- 全局
			confirmOrder(item) {
				uni.showLoading({
					title: '请稍后'
				});
				// 获取列表
				this.$api.post({
					url: '/wanlshop/order/confirmOrder',
					data: {
						id: item.id
					},
					success: res => {
						let {
							stateTip,
							stateTipColor
						} = this.orderStateExp(4);
						item = Object.assign(item, {
							state: 4,
							stateTip,
							stateTipColor
						});
						this.$store.commit('statistics/order', {
							receiving: this.$store.state.statistics.order.receiving - 1,
							evaluate: this.$store.state.statistics.order.evaluate + 1
						});
						uni.hideLoading();
					}
				});
			},
			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#333';
				switch (+state) {
					case 1:
						stateTip = '等待支付';
						stateTipColor = '#f40';
						break;
					case 2:
						stateTip = '等待卖家发货';
						break;
					case 3:
						stateTip = '卖家已发货';
						break;
					case 4:
						stateTip = '交易成功';
						break;
					case 5:
						stateTip = '交易成功';
						break;
					case 6:
						stateTip = '已完成';
						break;
					case 7:
						stateTip = '订单已关闭';
						stateTipColor = '#777';
						break;
					case 8:
						stateTip = '商家已接单';
						break;
					case 9:
						stateTip = '已到达自提点';
						break;
						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			},
			getRefund(status) {
				return ["退款", "退款中", "待退货", "退款完成", "退款关闭", "退款被拒"][status];
			},
			// 修改地址
			getsharePay() {
				this.$api.post({
					url: '/wanlshop/order/sharePay',
					data: {
						order_id: this.order_ids,
					},
					success: res => {}
				})
			},
			editAddress(id) {
				this.$wanlshop.to('/pages/user/address/address?source=2&order_id=' + id);
			},
			//添加或修改成功之后回调
			async refreshList(address_id, order_id) {
				uni.showLoading({
					title: '正在提交新地址'
				});
				// 获取列表
				this.$api.post({
					url: '/wanlshop/order/editOrderAddress',
					data: {
						id: order_id,
						address_id: address_id
					},
					success: res => {
						this.$wanlshop.msg('地址修改成功');
						uni.hideLoading();
					}
				});
			}
		},
		onShareAppMessage() {
			console.log(this.order_ids);
			if (this.order_ids && this.order_ids.length > 0) {
				console.log(this.order_ids);
				let _this = this
				this.getsharePay()
				return {
					title: '我选好材料啦，请你帮我付个款吧~',
					path: `/pages/user/money/paymentBehalf?order_ids=${this.order_ids.join(',')}`,
					imageUrl: 'https://img.aibbyp.com/wechatUser/xhcl.png', // 替换为实际分享图片URL
					success: (res) => {
						console.log('分享成功', res);
						_this.order_ids = []
						// 分享成功后的操作
					},
					fail: (err) => {
						_this.order_ids = []
						console.log('分享失败', err);
						// 分享失败后的操作
					}
				};
			}

		},
	};
</script>

<style>
	.margin-lr-bj-xx {
		margin: 0 12rpx;
	}

	page {
		height: 100%;
	}
</style>